// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use std::fs;
use std::path::Path;
use std::process::Command;
use lnk::ShellLink;

use tauri::Manager;
use tauri::CustomMenuItem;
use tauri::SystemTray;
use tauri::SystemTrayMenu;
use tauri::SystemTrayMenuItem;
use tauri::SystemTrayEvent;

extern crate winapi;
use winapi::um::winuser::*;
use winapi::um::shellapi::*;
use std::ptr;

//use crate::{
//  utils::{set_window_shadow}
//};

//mod utils;

fn main() {
  let quit = CustomMenuItem::new("quit".to_string(),"退出");
  let hide = CustomMenuItem::new("hide".to_string(), "最小化");
  let tray_menu = SystemTrayMenu::new()
    .add_item(quit)
    .add_native_item(SystemTrayMenuItem::Separator)
    .add_item(hide);
  let system_tray = SystemTray::new().with_menu(tray_menu);
  tauri::Builder::default()
    //.setup(|app| {
    //    set_window_shadow(app);
    //    Ok(())
    //})
    // ✅ 在这里传递自定义命令
    .invoke_handler(tauri::generate_handler![open, get_files_in_directory])
    .system_tray(system_tray)
    .on_system_tray_event(|app, event| menu_handle(app, event))
    .run(tauri::generate_context!())
    .expect("error while running tauri application");



}



#[tauri::command]
fn open(path: String){
// 要打开的软件的路径
    //let program_path = "C:\\Program Files\\Internet Explorer\\iexplore.exe";
    println!("成功打开软件{}",path);
    let shortcut = lnk::ShellLink::open(&path).unwrap();
    println!("{:#?}", shortcut);
    if let Some(linkInfo) = shortcut.link_info(){
        //println!("---------------{:#?}", linkInfo);
        if let Some(local_base_path) = linkInfo.local_base_path(){
           println!("#######{:#?}", local_base_path);
           //files.push(lnk_file_path);
           println!("The real path of the shortcut is: {}", local_base_path);
           // 使用 Command::new() 创建一个新的命令
           let mut cmd = Command::new(&local_base_path);

           // 如果需要传递参数，可以使用 arg() 方法
           //cmd.arg("https://www.example.com");

           // 执行命令
           match cmd.spawn() {
               Ok(_) => println!("成功打开软件"),
               Err(e) => {
                   eprintln!("打开软件时出错: {}", e);
                   if let Some(icon_location) = shortcut.icon_location(){
                      let mut cmd = Command::new(&icon_location);
                      match cmd.spawn() {
                          Ok(_) => println!("成功打开软件"),
                          Err(e) => eprintln!("打开软件时出错: {}", e)
                      }
                   }
               }


           }

        }

    }


}

//解析快捷方式的真实地址
fn resolve_shortcut_path(shortcut_path: &str) -> Option<String> {
    let path = Path::new(shortcut_path);

    if let Ok(metadata) = fs::metadata(path) {
        if metadata.file_type().is_symlink() {
            if let Ok(real_path) = fs::read_link(path) {
                if let Some(real_path_str) = real_path.to_str() {
                    return Some(real_path_str.to_string());
                }
            }
        }
    }

    None
}

// 在 Tauri 中调用该函数
#[tauri::command]
fn get_files_in_directory(path: String) -> Vec<String> {
    let mut files = Vec::new();
    read_directory(&path,&mut files);
    files

}

// 定义一个函数，用于读取文件目录并返回 Vec
fn read_directory(path: &str, files: &mut Vec<String>){
    if let Ok(entries) = fs::read_dir(path) {
        for entry in entries {
            if let Ok(entry) = entry {
                let subPath = entry.path();
                if subPath.is_dir() {
                    read_directory(subPath.to_str().unwrap(),files);
                } else {
                    if let Some(file_name) = entry.file_name().to_str() {
                        if file_name.ends_with(".lnk") && !file_name.contains("卸载") && !file_name.contains("Uninstall")
                            && !file_name.contains("uninstall") && !subPath.to_str().unwrap().contains("Accessories")
                            && !subPath.to_str().unwrap().contains("Administrative Tools") {
                            println!("Found .lnk file: {}", file_name);
                            files.push(file_name.to_owned()+"#@#"+subPath.to_str().unwrap());
                        }
                    }
                }
            }
        }
    }
}


fn menu_handle(app_handle: &tauri::AppHandle, event: SystemTrayEvent) {
  match event {
    SystemTrayEvent::LeftClick {
      position: _,
      size: _,
      ..
    } => {
      println!("鼠标-左击");
      app_handle.get_window("customization").unwrap().show();
    }
    SystemTrayEvent::RightClick {
      position: _,
      size: _,
      ..
    } => {
      println!("鼠标-右击");
    }
    SystemTrayEvent::DoubleClick {
      position: _,
      size: _,
      ..
    } => {
      println!("鼠标-双击");
    }
    SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
      "quit" => {
        std::process::exit(0);
      }
      "hide" => {
        let item_handle = app_handle.tray_handle().get_item(&id);
        let window = app_handle.get_window("customization").unwrap();


           //println!("#######{:#?}", result);
             if window.is_visible().unwrap() {
                window.hide();
                item_handle.set_title("显示窗口").unwrap();
                println!("1");
            }else{
                window.show();
                item_handle.set_title("最小化").unwrap();
                println!("2");
            }

      }
      _ => {}
    },
    _ => {}
  }
}